package com.transaction.stockseata.filter;


import com.transaction.stockseata.utils.RepeatedlyRequestWrapper;
import org.checkerframework.checker.units.qual.C;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author ausu
 * @version 1.0
 * @description: TODO
 *                让装饰后的RepeatedlyRequestWrapper生效
 * @date 2023/1/30 16:01
 */
@Component
@WebFilter(filterName = "myFilter", urlPatterns = {"/**"})
public class RepeatableReadJsonFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     *  如果请求数据类型是JSON的话， 就把HttpServletRequest换成RepeatedlyRequestWrapper, 然后让过滤器继续走下去。
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest &&
                StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request,response);
        }
        if (null == requestWrapper) {
            chain.doFilter(request,response);
        } else {
            chain.doFilter(requestWrapper,response);
        }
        System.out.println("晚上Filter:::::::::::::::::::::::::::::::::::::::");
    }

    @Override
    public void destroy() {

    }
}
